package com.teambsc4.todo.views

import android.content.Intent
import android.location.LocationManager
import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.ArrowDropDown
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import com.teambsc4.todo.App
import com.teambsc4.todo.viewmodel.StoreData
import com.teambsc4.todo.entities.TaskStatus
import com.teambsc4.todo.entities.taskPriority
import com.teambsc4.todo.viewmodel.MainPageViewModel
import kotlinx.coroutines.launch

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun CreateTaskButton(viewModel: MainPageViewModel) {

    val dataStore = remember {
        StoreData()
    }
    val context = LocalContext.current
    val scope = rememberCoroutineScope()
    val launcher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.OpenDocument()
    )
    {
        it?.let { uri ->
            context.contentResolver.takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION)
            scope.launch {
                dataStore.storeImage(context, uri.toString())
            }
        }
    }
    LaunchedEffect(key1 = true) {
        dataStore.getImage(context).collect {
            if (it != null) {
                viewModel.imageUri = Uri.parse(it)
                viewModel.updateImage(Uri.parse(it))
            }
        }
    }

    var showDialog by remember { mutableStateOf(false) }
    Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.BottomEnd) {
        Column(modifier = Modifier.padding(16.dp)) {
            Button(onClick = {
                showDialog = true
            }) {
                Text("Add Task")
            }
        }

        if (showDialog) {
            viewModel.clearInputFields()
            AlertDialog(
                onDismissRequest = { showDialog = false },
                title = { Text(text = "Add a Task") },
                text = {
                    Column {

                        TextField(value = viewModel.taskTitle,
                            onValueChange = { viewModel.updateTitle(it) },
                            label = { Text("Title") })

                        TextField(
                            value = viewModel.taskDescription,
                            onValueChange = { viewModel.updateDescription(it) },
                            label = { Text("Description") })

                        TextField(
                            viewModel.taskEndTime,
                            onValueChange = { viewModel.updateEndTime(it) },
                            label = { Text("EndTime(天后)") },
                            keyboardOptions = KeyboardOptions(
                                keyboardType = KeyboardType.Number
                            )
                        )

                        Row {
                            Column(modifier = Modifier.padding(5.dp)) {
                                DropdownMenu(
                                    expanded = viewModel.isDropdownExpanded,
                                    onDismissRequest = {
                                        viewModel.isDropdownExpanded = false
                                    }
                                ) {
                                    TaskStatus.forEach {
                                        DropdownMenuItem(
                                            text = { Text(text = it) },
                                            onClick = { viewModel.updateStatus(it) })
                                    }
                                }
                                Text(text = "Selected Status:\n ${viewModel.taskState}")
                                IconButton(onClick = { viewModel.isDropdownExpanded = true }) {
                                    Icon(
                                        imageVector = Icons.Default.ArrowDropDown,
                                        contentDescription = "Open Dropdown"
                                    )
                                }
                            }
                            Column(modifier = Modifier.padding(5.dp)) {
                                DropdownMenu(
                                    expanded = viewModel.isDropdownExpanded2,
                                    onDismissRequest = {
                                        viewModel.isDropdownExpanded2 = false
                                    }
                                ) {
                                    taskPriority.forEach {
                                        DropdownMenuItem(
                                            text = { Text(text = it.drop(2)) },
                                            onClick = { viewModel.updatePriority(it) })
                                    }
                                }
                                Text(text = "Selected Priority:\n ${viewModel.taskPriority.drop(2)}")
                                IconButton(onClick = { viewModel.isDropdownExpanded2 = true }) {
                                    Icon(
                                        imageVector = Icons.Default.ArrowDropDown,
                                        contentDescription = "Open Dropdown"
                                    )
                                }
                            }
                        }
                        Column {
                            Box(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .height(100.dp), contentAlignment = Alignment.Center
                            ) {
                                AsyncImage(
                                    model = viewModel.imageUri,
                                    contentDescription = null,
                                    modifier = Modifier
                                        .size(200.dp),
                                    contentScale = ContentScale.Crop
                                )
                            }
                            IconButton(onClick = {
                                launcher.launch(arrayOf("image/*"))
                            }) {
                                Icon(imageVector = Icons.Default.Add, contentDescription = "Add Photo")
                            }
                        }
                    }
                },
                confirmButton = {
                    Button(enabled = viewModel.isConfirmEnabled(), onClick = {
                        viewModel.confirmTaskButton()
                        showDialog = false
                        viewModel.clearInputFields()
                    }) {
                        Text("Add")
                    }
                },
                dismissButton = {
                    Button(onClick = {
                        showDialog = false
                        viewModel.clearInputFields()
                    }) {
                        Text("Cancel")
                    }
                }
            )
        }
    }
}
